unit Calc;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, RzEdit, RzButton, RzBckgnd, Mask, RzLabel;

type
  TForm1 = class(TForm)
    RzLabel1: TRzLabel;
    RzLabel2: TRzLabel;
    RzLabel3: TRzLabel;
    RzLabel4: TRzLabel;
    b: TRzNumericEdit;
    c: TRzNumericEdit;
    RzSeparator1: TRzSeparator;
    a: TRzNumericEdit;
    RzBitBtn1: TRzBitBtn;
    res: TRzMemo;
    procedure FormCreate(Sender: TObject);
    procedure RzBitBtn1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

  TX2Calc = class
    a, b, c: real;
    function Calculate( var x1, x2: real ): boolean; // if two roots then result = TRUE
    {     Special results:
      1) result = False and second root is -1:
         The equation has a solution only in complex numbers.
      2) result = False and second root is -2:
         root is any numbers.
    }
  end;

  

var
  Form1: TForm1;
  X2Calc: TX2Calc;

implementation
{$R *.dfm}

function TX2Calc.Calculate( var x1, x2: real ): boolean;
var d: real;
begin
  Result := false;
  x1 := 0; X2 := 0;
  If a <> 0 then begin
    d := sqr(b) - 4*a*c;
    if d < 0 then begin
      x2 := - 1; 
      MessageBox( Form1.handle, 'This version of calc can not'#13#10'work with complex numbers',
                          'Calculate error', MB_ICONERROR or MB_OK );
      Exit;
    end;
    x1 := ( - b - sqrt( d ) )/( 2*a );
    if d > 0 then begin
      x2 := ( - b + sqrt( d ) )/( 2*a );
      Result := true;
    end;
  end else begin
    if b <> 0 then
      x1 := - ( c/b )
    else begin
      x2 := - 2
    end;
  end;
end;


procedure TForm1.FormCreate(Sender: TObject);
begin
  X2Calc := TX2Calc.Create;
end;

procedure TForm1.RzBitBtn1Click(Sender: TObject);
var root1, root2: real;
begin
  X2Calc.a := a.Value;
  X2Calc.b := b.Value;
  X2Calc.c := c.Value;
  res.Clear;
  If X2Calc.Calculate( root1, root2 ) then begin
    res.Lines.Add( 'this equation has two roots:' );
    res.Lines.Add( 'root1 = ' + FloatToStr( round(root1*10000)/10000 ) );
    res.Lines.Add( 'root2 = ' + FloatToStr( round(root2*10000)/10000 ) );
  end else begin
    if root2 = - 1 then begin
      res.Lines.Add( 'Calculate error:' );
      res.Lines.Add( 'Calc can not work with complex numbers' );
      Exit;
    end;
    if root2 = - 2 then begin
      res.Lines.Add( 'root - any number.' );
      Exit;
    end;
    res.Lines.Add( 'this equation has only one root:' );
    res.Lines.Add( 'root = ' + FloatToStr( round(root1*1000)/1000 ) );
  end;
end;

end.
